package com.yu.mall.interceptor;

import com.alibaba.fastjson.JSON;
import com.yu.mall.util.LogUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Aspect
@Component
public class LogInterceptor {

    @Pointcut("execution(public * com.yu.mall.controller..*.*(..)) && !execution(* com.yu.mall.configuration.*.*(..)) ")
    public void log() {
    }

    @Before("log()")
    public void doBefore(JoinPoint joinPoint) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        LogUtil.info(LogUtil.formatLog("url",request.getRequestURL().toString()));
        LogUtil.info(LogUtil.formatLog("方式",request.getMethod()));
        LogUtil.info(LogUtil.formatLog("ip",request.getRemoteAddr()));
        String s = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
        LogUtil.info(LogUtil.formatLog("类_方法",s));
        Map<String, String[]> parameterMap = request.getParameterMap();
        if(parameterMap != null && parameterMap.size() > 0){
            try {
                LogUtil.info(LogUtil.formatLog("入参", JSON.toJSONString(parameterMap)));
            } catch (Exception e) {
                LogUtil.error("请求参数转json异常",e);
            }
        }
    }

}
